package com.apobates.forum.bucket.servlet;

import com.google.gson.Gson;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * bootstrap-fileinput 响应的类
 *
 * @author xiaofanku
 * @since 20200528
 */
public final class BootStrapFileInputResponse implements Serializable {
    private static final long serialVersionUID = -6282107321641518228L;
    private final String identity;
    private final String imageURL;
    
    public BootStrapFileInputResponse(String identity, String imageURL) {
        super();
        this.identity = identity;
        this.imageURL = imageURL;
    }
    
    //获得图片地址的文件名
    private String getFileName() {
        return imageURL.substring(imageURL.lastIndexOf("/") + 1);
    }
    
    /**
     * bootstrap-fileinput
     * {"data":[{"id":"101","name":"snapshot-20191101000913773.png","location":"http://center.test.com/imagestore/20191101/snapshot-20191101000913773.png"}],"success":true}
     *
     * @return
     */
    public String toJson() {
        BootStrapFileInputImageInfo bfi = new BootStrapFileInputImageInfo(identity, getFileName(), imageURL);
        Map<String, Object> data = Map.ofEntries(Map.entry("success", (null != bfi)), Map.entry("data", List.of(bfi)));
        return new Gson().toJson(data);
    }
    
    public static String error(String errorMessage) {
        return "{\"error\": \"" + errorMessage + "\"}";
    }
    
    private class BootStrapFileInputImageInfo implements Serializable {
        private static final long serialVersionUID = 1715055678204500090L;
        private final String id;
        private final String name;
        private final String location;
        
        public BootStrapFileInputImageInfo(String imageId, String imageFileName, String ImageAbsolutePath) {
            this.id = imageId;
            this.name = imageFileName;
            this.location = ImageAbsolutePath;
        }
        
        public String getId() {
            return id;
        }
        
        public String getName() {
            return name;
        }
        
        public String getLocation() {
            return location;
        }
    }
}